import os
from jinja2 import Template, Environment, FileSystemLoader
# from flask import render_template
import FileReader
import Link
import RSTRenderer


class WikiProcessor():
    """The WikiProcessor generates wiki contents from available files."""

    def __init__(self):
        super().__init__()

        self.file_reader = FileReader.FileReader()
        self.rst_renderer = RSTRenderer.RSTRenderer()

        self.pages_dir = os.path.join("static", "rst", "")

        self.template_env = Environment(loader=FileSystemLoader("templates"))
        self.template_env.globals["STATIC_PREFIX"] = os.path.join("/static", "")

    def get_index_page(self, filter_string=None):
        file_names = self.file_reader.get_files_list(self.pages_dir)
        file_names.sort()

        labels = [self.file_name_to_link_label(file_name)
                  for file_name in file_names]

        targets = [self.file_name_to_link_target(file_name)
                   for file_name in file_names]

        links = [Link.Link(labels[ind], targets[ind])
                 for ind in range(len(file_names))]

        template = self.template_env.get_template("index.j2")
        return template.render(links=links)
        # return render_template("index.j2", links=links)  # only with flask

    def get_page_by_name(self, page):
        page_rst_content = self.file_reader.file_as_string(
            os.path.join(self.pages_dir, page + ".rst"))
        page_html = self.rst_renderer.render_string(page_rst_content)

        template = self.template_env.get_template("page.j2")
        return template.render(page_content=page_html)
        # return render_template("page.j2", page_content=page_html)  # only with flask

    def file_name_to_link_label(self, file_name):
        return file_name.replace("_", " / ")[:-4]

    def file_name_to_link_target(self, file_name):
        return "/page/" + file_name[:-4]
